<?php


/**
 * Server-side autocomplete text box. Whenever the user types stuff
 * in this text box, an asynchronous Ajax request to the server will
 * be sent, looking for potential matches.
 *
 * @package Controls
 */
class AjaxModCompleteTextBox extends QAutoCompleteTextBoxBase {
    private $strCallback;
    /**
     * QControl/QForm, which has the method to call in case of "onselect" event.
     * Use QAjaxAutoCompleteTextBox::SetSelectCallback($objObject, $strMethod) to set.
     * @var QControl|QForm
     */
    protected $objSelectCallbackObject;
    /**
     * Method, which will be called in case of "onselect" event
     * Use QAjaxAutoCompleteTextBox::SetSelectCallback($objObject, $strMethod) to set.
     * @var string
     */
    protected $strSelectCallbackMethod;

    /**
     * Control proxy, which handles events
     * @var QControlProxy
     */
    public $pxy;

    public function __construct($objParentObject, $strCallback, $strControlId = null) {
        parent::__construct($objParentObject, $strControlId);

        $this->strCallback = $strCallback;
        $this->pxy = new QControlProxy($this);
        $this->pxy->AddAction(new QAutoCompleteTextBoxEvent(), new QAjaxControlAction($this, 'callbackAjax'));
    }

    /**
     * Sets callback to method, which will be executed in case of "onselect" event (when suggested item is selected)
     * @param QControl|QForm $objControl
     * @param string $strMethod
     */
    public function SetSelectCallback($objControl, $strMethod) {
        $this->objSelectCallbackObject = $objControl;
        $this->strSelectCallbackMethod = $strMethod;
        $this->pxy->AddAction(new QSelectEvent(), new QAjaxControlAction($this, 'txt_Select'));
    }

    public function txt_Select($strFormId, $strControlId, $strParameter) {


        $objControl = $this->objSelectCallbackObject;
        $strMethod = $this->strSelectCallbackMethod;
        if ($objControl) {
            $objControl->$strMethod($strParameter);
        }
    }
    public function callbackAjax($strFormId, $strControlId, $strParameter) {

        $parent = (isset($this->objParentControl) ? $this->objParentControl : $this->objForm);
        try {
            $arrToSerialize = $parent->{$this->strCallback}($strParameter);
        } catch (Exception $e) {
            echo "There's been an error processing auto-complete matches: \n";
            throw $e;
        }

        if (is_null($arrToSerialize)) {
            return;
        }

        if (!is_array($arrToSerialize)) {
            echo 'Error: the callback method for QAutoCompleteTextBox must return an array of strings';
            throw new QCallerException("callback method for QAutoCompleteTextBox must return an array of strings");
        }

        foreach ($arrToSerialize as $item) {
            echo $item . "\n";
        }

        // Critically important - stop the processing and don't allow any other
        // QCubed events to fire in this case
        exit;
    }

    public function GetScript() {
        if(!$this->blnVisible || !$this->blnEnabled) {
            return '';
        }

        // TODO: escape jquery => $
        return sprintf('

    var objParams = {Qform__FormId:"%s",Qform__FormControl:"%s"};
    $("#%s").autocomplete("%s",
									{extraParams:objParams,
									%s%s%s%s%s%s%s})%s',
                $this->objForm->FormId,
                $this->pxy->ControlId,
                $this->strControlId,
                QApplication::$RequestUri,
                "minChars:" . $this->intMinChars,
                (($this->blnAutoFill)		? ",autoFill:true" : ""),
                (($this->blnMatchContains)	? ",matchContains:true" : ""),
                (($this->blnMatchCase) 		? ",matchCase:true" : ""),
                (($this->blnMustMatch)		? ",mustMatch:true" : ""),
                (($this->Width)				? ",width:" . $this->Width : ""),
                (($this->strTextMode == QTextMode::MultiLine) ? ",multiple:false" : ""),
                // functionality for "onselect"
                ($this->objSelectCallbackObject ? sprintf(".result(function(event, data, formatted) {
    var strParam = '';
    if (data[1]) {
    strParam = data[0] + '|' + data[1];
    } else {
    strParam = data;
    }
									qc.pA('%s', '%s', '%s', strParam, '%s');
									})",
                $this->objForm->FormId, $this->pxy->ControlId, 'QSelectEvent',
                $this->objForm->DefaultWaitIcon ? $this->objForm->DefaultWaitIcon->ControlId : '')
                : ""
                )
        );
    }
}
?>